# -*- coding: utf-8 -*-
# @Author: kaiquan
# @Date: 2025/7/25
# File: check_network
import base64
import re
import time
import requests
from core.new_device import Device
from loguru import logger
import random


def check_network(d, user_id=0):
    logger.info(f"{d.serial} Checking network for user {user_id}...")

    # 检查 tun0 接口（全局网络接口）
    ip_info, code = d.shell("ip a | grep tun0")
    for i in range(2):
        if code >= 0:
            if 'tun0' in ip_info:  # tun0 存在
                # 在 user_id 的上下文中运行 curl
                test_proxy_info, code = d.shell(
                    'curl --connect-timeout 10 -s -w "%{http_code}" -k https://www.google.com/generate_204')
                logger.info(f"{d.serial} google_204 for user {user_id}: {test_proxy_info} {code}")
                if '204' in test_proxy_info:
                    return True
    logger.warning(f"{d.serial} Network check failed for user {user_id}")
    return False
    # return d.shell(f'curl --connect-timeout 5  http://m.google.com/').exit_code == 0


def fetch_proxys(d: Device, v4=True):
    try:
        for i in range(3):
            r = requests.get(
                'https://crawl-fs.datatell.com.cn/sy_proxy?key=7mkLlwBfmhSEVd6sWp2DZUGAtKtyjgqh7rGoKtni1mQ=',
                timeout=10)
            if r.status_code == 200:
                ssrs = base64.b64decode(r.text).splitlines()
                ssr_list = [line.decode('utf-8') for line in ssrs if line.strip()]
                if v4:
                    v4_proxys = get_v4_proxys(ssr_list)
                    if v4_proxys:
                        return v4_proxys
                    else:
                        return ssr_list

                else:
                    return ssrs
        return []
    except Exception as e:
        logger.info(f"{d.serial} Error fetching proxy list: {e}")
    return []


def get_v4_proxys(proxys):
    proxies = []
    for ssr in proxys:
        try:
            proxy = base64.b64decode(ssr.split('//')[1]).decode('utf-8')
            remarks = re.search(r'remarks=(.*?)&', proxy)
            if remarks:
                remarks = safe_b64decode(remarks.group(1))
                if 'v4' in remarks.lower():
                    proxies.append(ssr)
        except Exception as e:
            # logger.info(f"{d.serial} Error fetching proxy list: {e}")
            continue
    return proxies


def safe_b64decode(b64_str):
    # 计算需要添加的 padding
    missing_padding = len(b64_str) % 4
    if missing_padding:
        b64_str += '=' * (4 - missing_padding)
    try:
        decoded_bytes = base64.b64decode(b64_str.replace('-', '+').replace('_', '/'))
        return decoded_bytes.decode('utf-8')
    except Exception as e:
        print(f"解码失败: {e}")
        return ""


def set_ssr_proxy(d: Device, ssr_list: list, user=0):
    d.shell(f"am force-stop --user {user} com.bige0.shadowsocksr")
    time.sleep(2)
    d.shell(f"am start --user {user} -n com.bige0.shadowsocksr/.Shadowsocks")
    time.sleep(3)

    d.click("com.bige0.shadowsocksr:id/fab")
    time.sleep(2)
    d.click("OK")

    if check_network(d, user):
        # 代理app关闭了
        return True
    logger.warning(f"{d.serial} Proxy is invalid !!!")
    # 代理无效
    for i in range(10):
        ssr = random.choice(ssr_list)
        d.shell(f"am force-stop --user {user} com.bige0.shadowsocksr")
        time.sleep(2)
        d.shell(
            f'am start --user {user} -W -a com.bige0.shadowsocksr.ProfileManagerActivity --es ssr_data "{ssr}" --ez onlyuser false ')
        time.sleep(5)
        if check_network(d, user):
            return True
        time.sleep(3)
    return False


def set_ssr_proxy_v2(d: Device, ssr_list: list, user=0):
    ssr = random.choice(ssr_list)
    d.shell(f"am force-stop --user {user} com.bige0.shadowsocksr")
    time.sleep(2)
    d.shell(
        f'am start --user {user} -W -a com.bige0.shadowsocksr.ProfileManagerActivity --es ssr_data "{ssr}" --ez onlyuser false ')
    time.sleep(5)


def setting_network(d: Device, user=0, v4=True):
    try:
        if check_network(d, user):
            logger.info(f"{d.serial} Network is OK !!!")

            if str(user) != "0":
                proxys = fetch_proxys(d, v4=v4)
                if set_ssr_proxy_v2(d, proxys, user):
                    logger.info(f"{d.serial}  proxy is OK !!!")
                    return True
            else:
                return True
        else:
            proxys = fetch_proxys(d, v4=v4)
            if set_ssr_proxy(d, proxys, user):
                logger.info(f"{d.serial}  proxy is OK !!!")
                return True
            else:
                return False
    except Exception as e:
        logger.error(f"{d.serial} Error setting network: {e}")
        return False


if __name__ == '__main__':

    d = Device("476caabd")
    fetch_proxys(d)
    ssrs = [
        'ssr://NDcuMTA4LjYyLjU0OjIwODE6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